package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.entity.*;
import com.entity.Ground;
import com.entity.User;
import com.entity.pageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mapper.UserMapper;
import com.service.MSGService;
import com.service.UserService;
import com.untils.JwtUtil;
import com.untils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    private MSGService jwtService;

    /**
     * 登录
     *
     * @param user 用户
     * @return 成功：返回用户令牌，错误：返回错误信息
     */
    @Override
    public String login(User user) {
        System.out.println("进入login");
        List<User> selectedList = list(new LambdaQueryWrapper<User>()
                .eq(User::getUname, user.getUname()));
        if (selectedList.isEmpty()) {
            throw new RuntimeException("账号不存在哦 请先注册吧~");
        }
        User selected = selectedList.get(0);
        String encodedPassword = selected.getPsw();
        // 判断密码是否正确
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean result = passwordEncoder.matches(user.getPsw(), encodedPassword);
        System.out.println("经过密码判断，结果：" + result);
        // 暂时不进行验证，注册写完再说
        if (!result) {
            throw new RuntimeException("账号或密码有误 请再检查检查~");
        }
        // 生成令牌
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("uname", selected.getUname());
        map.put("mobile", selected.getMobile());
        map.put("psw", selected.getPsw());
        System.out.println("返回令牌，令牌为：" + JwtUtil.generateToken(map));
        return JwtUtil.generateToken(map);
    }

    /**
     * 检验手机号是否可以
     *
     * @param mobile 传入手机号
     * @return 返回执行状态
     */
    @Override
    public String hasRegister(String mobile) {
        if (userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getMobile, mobile)).isEmpty()) {
            System.out.println("返回Success");
            return "Success";
        }
        System.out.println("返回Error");
        return "Error";
    }

    /**
     * 进行注册操作 对密码加密
     *
     * @param user 用户信息
     * @return 返回成功与否的统一结果集
     */
    @Override
    public String register(User user) {
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.getPsw());
        user.setPsw(encodedPassword);
        user.setAge(18);
        userMapper.insert(user);
        return "Success";
    }

    /**
     * 随机数设置验证码
     *
     * @param phone 发送手机号
     * @return 返回发送结果
     */
    @Override
    public boolean sendMsm(String phone) {
        //生成随机数
        String code = RandomUtil.getFourBitRandom();
        Map map = new HashMap();
        map.put("code", code);
        return jwtService.send(map, phone);
    }

    @Override
    public List<Map<String,Object>> PInfo(String uname){
        return  userMapper.PInfo(uname);
    }

//    @Override
//    public List<Ground> getAllGround() {
//
//        return userMapper.getAllGround();
//    }

//    @Override
//    public List<Ground> search(String cCampus,String cType){
//
//        return  userMapper.search(cCampus,cType);
//    }
//    @Override
//    public List<Ground> searchByCampus(String cCampus) {
//        return userMapper.getByCampus(cCampus);
//    }
//
//    @Override
//    public List<Ground> searchByType(String cType) {
//        return userMapper.getByType(cType);
//    }

    @Override
    public pageBean getAllGround(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<Ground> ground = userMapper.getAllGround();
        Page<Ground> p = (Page<Ground>)ground;

        pageBean page = new pageBean(p.getTotal(),p.getResult());
        return page;
    }

    @Override
    public pageBean search(String cCampus,String cType,int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);

        List<Ground> ground = userMapper.search(cCampus,cType);
        Page<Ground> p = (Page<Ground>)ground;

        pageBean page = new pageBean(p.getTotal(),p.getResult());
        return page;
    }
    @Override
    public pageBean searchByCampus(String cCampus,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<Ground> ground = userMapper.getByCampus(cCampus);
        Page<Ground> p = (Page<Ground>)ground;

        pageBean page = new pageBean(p.getTotal(),p.getResult());
        return page;
    }

    @Override
    public pageBean searchByType(String cType,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<Ground> ground = userMapper.getByType(cType);
        Page<Ground> p = (Page<Ground>)ground;

        pageBean page = new pageBean(p.getTotal(),p.getResult());
        return page;
    }

    @Override
    public User info(String mobile) {
        System.out.println("info传入的mobile值为:" + mobile);
        List<User> selectedList = list(new LambdaQueryWrapper<User>()
                .eq(User::getMobile, mobile));
        if (selectedList.isEmpty()) {
            throw new RuntimeException("info报错报错未知错误！");
        }
        return selectedList.get(0);
    }

    @Override
    public String update(User user) {
        System.out.println("update传入的user为：" + user);
        userMapper.update(user, new LambdaQueryWrapper<User>()
                .eq(User::getMobile, user.getMobile()));
        return "Success";
    }

    @Override
    public String updateP(String GID, String TID, String PDATE) {
        userMapper.UpdataP(GID, TID, PDATE);
        return "Success";
    }

    /**
     * 添加预约记录
     * @param ruleForm 预约信息对象
     * @param uid 预约用户id
     * @return 返回状态
     */
    @Override
    public String addPreorder(RuleForm ruleForm, int uid){
        userMapper.addPreorder(ruleForm.getG_id(),ruleForm.getT_id(),uid,ruleForm.getP_date());
        return "Success";
    }

    @Override
    public String forget(User user){
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.getPsw());
        user.setPsw(encodedPassword);
        userMapper.forget(user.getPsw(), user.getMobile());
        return "Success";
    }
}
